package main

import(
	"github.com/gin-gonic/gin"
	"crypto/md5"
	"fmt"
	"time"
	"encoding/hex"
	"net/http"
)

var users map[string]string

func init()  {
	users = make(map[string]string)
}

func calcMd5(data []byte) string {
	h := md5.New()
	h.Write(data)
	cipherStr := h.Sum(nil)
	return hex.EncodeToString(cipherStr)
}

func checkLogin(c *gin.Context)  (string,bool){
	if cookie,_:=c.Request.Cookie("session_id");cookie!=nil{
		if user,ok:=users[cookie.Value];ok{
			return user,true
		}
	}
	return "",false
}

func doLoginTransaction(phone string,c *gin.Context)  {
	nowTime:=time.Now().UnixNano()
	sessionID:=fmt.Sprintf("%s_%d",phone,nowTime)
	sessionID = calcMd5([]byte(sessionID))
	users[sessionID] = phone
	cookie := http.Cookie{Name: "session_id", Value: sessionID, Path: "/", MaxAge: 86400}
	http.SetCookie(c.Writer, &cookie)
}